#!/bin/bash

export PATH=/sbin:/bin:/usr/sbin:/usr/bin

DIR=$(dirname $(readlink -f "$0"))
SERVER=/opt/vyatta/sbin/zvr
HOMDIR=/home/vyos/zvr
LOGFILE=$HOMDIR/zvr.log
BOOTLOG=$HOMDIR/zvrstartup.log
LOCKFILE=$HOMDIR/.vyosfilelock

if [ $# -eq 0 ]; then
    echo "usage: $0 [start|stop|restart|status]"
    exit 1
fi

err_exit() {
    echo $1
    exit 1
}

LOG_DIR=`dirname $LOGFILE`; mkdir -p $LOG_DIR

# ETH0_IP=`ip route | grep eth0 | awk '{printf $9}'`
# for ZSTAC-19196 zhanyong.miao
ETH0_IP=`ip -4 -o a show dev eth0 primary | awk '{print $4; exit}' | cut -f1 -d '/'`
if [ x$ETH0_IP == "x" ]; then
   err_exit "unable to get the IP of eth0"
fi

cleanup_tmp_dir() {
    rm -rf /tmp/tmp-log
}

get_pid() {
    echo $(pgrep -x zvr)
}

check_status() {
    pid=$(get_pid)

    if [ x"$pid" = x"" ]; then
        # stopped
        echo "1"
        return 1
    else
        # running
        echo "0"
        return 0
    fi
}

server_status() {
    check_status
    ret=$?
    if [ $ret -eq 0 ]; then
        pid=$(get_pid)
        echo "zstack virtual router agent [PID:$pid] is running"
    elif [ $ret -eq 1 ]; then
        echo "zstack virtual router agent is stopped"
    fi

    exit $ret
}

do_start() {
    cleanup_tmp_dir
    chown -R vyos:users $HOMDIR
    su - vyos -c "echo $(date) start zstack virtual router >> $BOOTLOG"
    su - vyos -c "nohup $SERVER -ip $ETH0_IP -logfile $LOGFILE >>$BOOTLOG 2>&1 < /dev/null &"

    sleep 1

    retry=1
    maxRetries=10
    until [ ${retry} -ge ${maxRetries} ]
    do
        c=$(check_status)
        if [ x"$c" = x"1" ]
        then
            echo "failed, retrying the $retry time"
            su - vyos -c "echo $(date) start zstack virtual router failed, retrying the $retry time >> $BOOTLOG"
            su - vyos -c "nohup $SERVER -ip $ETH0_IP -logfile $LOGFILE >>$BOOTLOG 2>&1 < /dev/null &"
            sleep $(( retry++ ))
        else
            ((retry=maxRetries+1))
        fi
    done

    check_status > /dev/null || err_exit "unable to start zstack virtual router agent"

    exit 0
}

start_server() {
    check_status
    ret=$?
    if [ $ret -eq 0 ]; then
        pid=$(get_pid)
        echo "zstack virtual router agent [PID:$pid] is running already"
        su - vyos -c "echo $(date) zstack virtual router agent [PID:$pid] is running already >> $BOOTLOG"
    elif [ $ret -eq 1 ]; then
        do_start
    fi
}

do_stop() {
    pid=$(get_pid)
    su - vyos -c "echo $(date) stop virtual router agent pid: $pid >> $BOOTLOG"
    if [ x"$pid" != x"" ]; then
        kill -SIGINT $pid
        sleep 1
        kill -SIGTERM $pid 2> /dev/null
        while kill -0 $pid 2> /dev/null; do
            su - vyos -c "echo $(date) stop virtual router agent pid: $pid >> $BOOTLOG"
            sleep 1
        done
    fi
}

stop_server() {
    check_status
    ret=$?
    if [ $ret -ne 0 ]; then
        echo "zstack virtual router agent stopped already"
        su - vyos -c "echo $(date) zstack virtual router agent stopped already >> $BOOTLOG"
        return
    fi
    (
        flock -e 300
        do_stop
    ) 300>$LOCKFILE

}

restart_server() {
    pid=$(get_pid)
    if [ x"$pid" == x"" ]; then
        start_server
        return
    fi

    # generate tmp guard script
    TMP=$SERVER.guard.$$
    trap "rm -f $TMP 2>/dev/null" EXIT
    echo "sleep 3" > $TMP
    sudo -u vyos bash $TMP &

    echo "backgroup pid: $!"
    disown $!

    stop_server
    start_server
}

CMD="$1"
case "$CMD" in
    start) start_server ;;
    stop) stop_server ;;
    status) server_status ;;
    restart) restart_server ;;
esac

# vim: et ai ts=4 sw=4
